package org.gd.hellojson.locale;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.SerializerFactory;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.StdSerializerProvider;

import java.lang.reflect.Field;

/**
 * @author Gorhover
 * @version 1.0-SNAPSHOT
 * @since 2013-11-07 19:53
 */
public class MessageSourceStdSerializerProvider
        extends StdSerializerProvider
        implements ObjectHolder {

    private Object object;

    private static SerializerFactory getSerializerFactory(SerializerProvider serializerProvider) {
        Field field = null;
        try {
            field = StdSerializerProvider.class.getDeclaredField("_serializerFactory");
            field.setAccessible(true);
            return (SerializerFactory)(field.get(serializerProvider));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        } finally {
            if(field != null) {
                field.setAccessible(false);
            }
        }
        return null;
    }

    public MessageSourceStdSerializerProvider(Object object,
                                              ObjectMapper objectMapper) {
        this(object,
                objectMapper.getSerializationConfig(),
                objectMapper.getSerializerProvider());
    }

    public MessageSourceStdSerializerProvider(Object object,
                                              SerializationConfig serializationConfig,
                                              SerializerProvider serializerProvider) {
        this(serializationConfig,
                (StdSerializerProvider) serializerProvider,
                getSerializerFactory(serializerProvider));
        this.object = object;
    }

    private MessageSourceStdSerializerProvider(SerializationConfig serializationConfig,
                                              StdSerializerProvider serializerProvider,
                                              SerializerFactory serializerFactory) {
        super(serializationConfig, serializerProvider, serializerFactory);
    }

    @Override
    protected MessageSourceStdSerializerProvider createInstance(SerializationConfig serializationConfig,
                                                                SerializerFactory serializerFactory) {
        return new MessageSourceStdSerializerProvider(
                serializationConfig, this, serializerFactory)
                .setObject(getObject());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object getObject() {
        return object;
    }

    private MessageSourceStdSerializerProvider setObject(Object object) {
        this.object = object;
        return this;
    }
}
